/**
 * 开单页-结算信息区
 */
import React, { useEffect, useRef, useState, useImperativeHandle, forwardRef } from 'react';
import { Button, Divider, FormInstance, Badge, Row, Col } from 'antd';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import { useModel } from 'umi';
import { isNull } from '@/utils/utils';
import PermissionControl from '@/components/PermissionControl';

interface SettlementInfoProps {
  onFinish: (values: any) => void;
  goodsList: STOCKGOODSAPI.GoodsItem[];
  settleInfo: any;
  type?: string;
  onCancel: Function
}

const SettlementInfo: React.FC<SettlementInfoProps> = forwardRef((props, ref) => {
  const { onFinish, goodsList = [], settleInfo = null, onCancel } = props;
  const { initialState } = useModel('@@initialState');
  const formRef = useRef<FormInstance>();

  // 商品总价
  const [goodsTotalPrice, setGoodsTotalPrice] = useState<number>(0);

  // 商品数量
  const [goodsNum, setGoodsNum] = useState<number>(0);

  useEffect(() => {
    let goodsNum1 = 0, goodsTotalPrice1 = 0;
    goodsList.forEach(item => {
      if (item.goods_id) {
        goodsTotalPrice1 += Number(item.goods_total_price as number);
        setGoodsTotalPrice(parseFloat(goodsTotalPrice1).toFixed(2));

        goodsNum1 += item.goods_num as number;
        setGoodsNum(goodsNum1);
      }
    });
  }, [goodsList]);

  useEffect(() => {
    // 结算信息有值，则填充数据
    if (!isNull(settleInfo.total_price)) {
      formRef.current?.setFieldsValue({
        goodsTotalPrice: settleInfo.sett_price,
        apply_oper_name: settleInfo.order_person,
      });
    } else {
      // 默认把当前登录人名称填充到订单负责人
      formRef.current?.setFieldsValue({
        apply_oper_name: initialState?.currentUser?.oper_name,
      });
    }
  }, [settleInfo]);

  // 暴露的子组件方法，给父组件调用
  useImperativeHandle(ref, () => ({
    submit: () => {
      // formRef.current.submit();
      onSubmitForm();
    },
    clear: () => {
      formRef.current?.resetFields();
      setGoodsTotalPrice(0);
      setGoodsNum(0);
      formRef.current?.setFieldsValue({
        apply_oper_name: initialState?.currentUser?.oper_name,
      });
    }
  }))

  // 发起支付
  const onSubmitForm = async () => {
    try {
      await formRef.current?.validateFields();
      const values = formRef.current?.getFieldsValue();
      const data = {
        ...values,
        goods_total_price: goodsTotalPrice,
        goods_num: goodsNum,
      }
      // 点击保存订单，一般停留在当前页
      await onFinish(data);
    } catch (error) {
      console.error(error);
    }
  }

  return <div className="service-record">
    <div className="header">
      <div className="title" style={{ width: '100%' }}>3.订单汇总</div>
    </div>
    <Divider style={{ margin: '10px 0' }} />

    <ProForm
      className="order-pro-form"
      formRef={formRef}
      scrollToFirstError
      submitter={{
        render: () => {
          return <div style={{ textAlign: 'right' }}>
            <PermissionControl action_id="400400001">
              <Button style={{ marginRight: 10 }} key="save" type="primary" onClick={async () => {
                onSubmitForm();
              }}>提交订单</Button>
            </PermissionControl>
            <PermissionControl action_id="400400007">
              <Button key="calcel" onClick={() => onCancel()}>取消订单</Button>
            </PermissionControl>
          </div>
        }
      }}
      onFinish={async (values) => {
        onFinish(values);
      }}
      labelCol={{ flex: '0 0 90px' }}
      layout="horizontal"
    >
      <Row style={{ width: 1000 }}>
        <Col span={5}>
          <ProForm.Item label="商品数量">
            <span style={{ color: '#F5232D', fontWeight: 'bold' }}>{goodsNum}</span>（件）
          </ProForm.Item>
        </Col>
        <Col span={5}>
          <ProForm.Item label="订单金额">
            {goodsTotalPrice} （元）
          </ProForm.Item>
        </Col>
        <Col span={8}>
          <ProFormText
            name="apply_oper_name"
            label="订单负责人"
          />
        </Col>
      </Row>
    </ProForm>
  </div>
});
export default SettlementInfo;
